<?php
	require_once ("./General/dbConnection.php");
	require_once ("./General/validate.php");
	require_once("./Model/m_Logger.php");
	
	class RegisterHandler{
		//TODO skapa EN dbConnection i index.php och skicka med som parameter
		public function CheckIfRegistered($User){

		
		$db = new DBConnection();
		$db->Connect();
		$sql = "SELECT COUNT(*) FROM users WHERE Username = ?";
		$stmt = $db->Prepare($sql);
		$stmt->bind_param("s", $User);
		if ($stmt === FALSE) {
			echo "CIR STMT";
            return false;
        }
        $stmt->execute();
		//$stmt->store_result();
		$numrows = $stmt->num_rows;
		$stmt->close();

		
		if($numrows == 1) {
			return true;
		}
		
		return false;	
		}
		
		public function RegisterToDB($NewUser, $NewPassword){
		$db = new DBConnection();
		$db->Connect();
		$sql = "INSERT INTO users(UID, Username, Password) VALUES (NULL,?,?)";
        $stmt = $db->prepare($sql);
		$NewPassword = sha1($NewPassword);           
        $stmt->bind_param("ss", $NewUser, $NewPassword);
        if ($stmt === FALSE) {
            return false;
        }
	    $stmt->execute();                 
		if($stmt->affected_rows == -1){
			return true;
		}
		$stmt->close(); 
        return false;
		}
		
		public function RemoveFromDB($DeleteUser){
		$db = new DBConnection();
		$db->Connect();
		$sql = "DELETE FROM users  WHERE Username = ?";
	    $stmt = $db->Prepare($sql);               
		$stmt->bind_param("s", $DeleteUser);
		$stmt->execute();
		$stmt->Close();	
		unset($_SESSION[$DeleteUser]);
		if($this->CheckIfRegistered($DeleteUser) == false){
			return true;
		}
		
		return false;
		}
		
	}
